<template>
	<div>
		<div>PDF编辑</div>
		<button @click="init">init</button>
    <button @click="init2">init2</button>
		<iframe id="preview" frameborder="0" width="100%" height="900px" ref="preview"></iframe>
		<div ref="map" id="earthMap" style="width: 1650px; height: 600px"></div>
	</div>
</template>

<script>
	import mapboxgl from "mapbox-gl";
	import "mapbox-gl/dist/mapbox-gl.css";
	import JSPDF from 'jspdf'
	import 'jspdf-autotable'
	export default {
		data() {
			return {
				mapToken: 'pk.eyJ1IjoibGVpeXV5YW4iLCJhIjoiY2trZzltajd6MGhsMDJvcW43bHBna3c2biJ9.OE_79L9HaZAe6nnr8VYLTA'
			}
		},
		beforeCreate() {
			//main()
			Promise.all([
				import('../../public/pdf/simfang-normal'),
				import('../../public/pdf/simhei-bold'),
				import('../../public/pdf/simhei-normal')
			]).then(m => console.log('加载完毕：', m));
		},
		created() {
			Array.prototype.groupBy = function(field, g, c) {
				let fieldName = !!g ? g : field;
				let childName = !!c ? c : 'children';
				let array = [];
				let groupNames = new Set();
				while (this.length > 0) {
					let obj = this.shift();
					groupNames.add(obj[field]);
					array.push(obj);
				}
				for (let name of groupNames) {
					this.push({
						[fieldName]: name,
						[childName]: array.filter(item => name == item.year)
					})
				}

			}
		},
		mounted() {

		},
		methods: {
			init() {
				Promise.all([
					import('../../public/pdf/simfang-normal'),
					import('../../public/pdf/simhei-bold'),
					import('../../public/pdf/simhei-normal')
				]).then(m => {
					this.getDownLoadPdf();
				});
			},
      init2() {
      	Promise.all([
      		import('../../public/pdf/simfang-normal'),
      		import('../../public/pdf/simhei-bold'),
      		import('../../public/pdf/simhei-normal')
      	]).then(m => {
      		this.initMap();
      	});
      },
			dataURLtoBlob(dataurl) {
				let arr = dataurl.split(","); //注意base64的最后面中括号和引号是不转译的
				let _arr = arr[1].substring(0, arr[1].length - 2);
				let mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(_arr),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime,
				});
			},
			getDownLoadPdf() {
				var doc = new JSPDF({
					orientation: "p",
					unit: "pt"
				});
				//添加并设置字体
				doc.addFont('simhei-normal.ttf', 'simhei', 'normal');
				doc.addFont('simhei-bold.ttf', 'simhei', 'bold');
				doc.setFont('simfang');
				const pdfHrigth = 841.89;
				doc.addImage(
					require('/src/assets/baojiadan/baojiadanlogo.png'),
					"PNG",
					0,
					0,
					595.28,
					0
				);
				// 设置字体大小
				doc.setFontSize(10);
				doc.text(
					`尊敬的客户：`,
					20,
					200
				);
				doc.text(
					`非常感谢您对定制包机的信赖，我们荣幸地为您提供本次行程报价方案，具体如下：`,
					40,
					220
				);
				// 行程信息
				doc.setFontSize(16);
				doc.text("行程信息", 20, 250);
				doc.setDrawColor(128, 128, 128);
				doc.setLineWidth(1.5);
				doc.line(20, 260, 85, 260);
				var columns = [{
						title: "出发日期",
						dataKey: "scheduleDepartureTime"
					},
					{
						title: "出发城市",
						dataKey: "departureCityName"
					},
					{
						title: "到达城市",
						dataKey: "destinationCityName"
					},
					{
						title: "人数",
						dataKey: "custNum"
					},
					{
						title: "备注",
						dataKey: "remark"
					},
				];
				let rows = [];
				for (let i = 0; i < 1; i++) {
					rows.push({
						scheduleDepartureTime: '2021-9-8 16:30',
						departureCityName: '西安' + '\r\n' + 'XIA',
						destinationCityName: '上海',
						custNum: 1,
						remark: '二元墙塌了'
					});
				}
				doc.autoTable(columns, rows, {
					styles: {
						font: "simhei",
						fontStyle: "normal",
						overflow: "linebreak",
						lineColor: [166, 166, 166],
						lineWidth: 0.5,
						halign: "center",
					},
					headStyles: {
						fillColor: [191, 191, 191],
						textColor: [0, 0, 0],
					},
					bodyStyles: {
						textColor: [0, 0, 0],
					},
					theme: "grid",
					pageBreak: "avoid",
					startY: 270,
					margin: {
						left: 17,
						right: 15
					},
				});
				if (pdfHrigth - 30 - doc.autoTable.previous.finalY < 45) {
					doc.addPage();
					doc.autoTable(0, [{
						id: ""
					}], {
						styles: {
							cellWidth: "auto",
							font: "simhei",
							fontStyle: "normal",
							lineColor: [166, 166, 166],
							minCellHeight: 25,
						},
						theme: "plain",
						startY: 25,
						margin: {
							left: 15,
							right: 15
						},
						didDrawCell: (data) => {
							// 推荐方案
							doc.setFontSize(16);
							doc.setTextColor(0, 0, 0);
							doc.text("推荐方案", 20, data.cell.y + 15);
							doc.setDrawColor(128, 128, 128);
							doc.setLineWidth(1.5);
							doc.line(20, data.cell.y + 25, 85, data.cell.y + 25);
						},
					});
				} else {
					doc.autoTable(0, [{
						id: ""
					}], {
						styles: {
							cellWidth: "auto",
							font: "simhei",
							fontStyle: "normal",
							lineColor: [166, 166, 166],
							minCellHeight: 25,
						},
						theme: "plain",
						startY: doc.autoTable.previous.finalY + 20,
						margin: {
							left: 15,
							right: 15
						},
						didDrawCell: (data) => {
							// 推荐方案
							doc.setFontSize(16);
							doc.setTextColor(0, 0, 0);
							doc.text("推荐方案", 20, data.cell.y + 15);
							doc.setDrawColor(128, 128, 128);
							doc.setLineWidth(1.5);
							doc.line(20, data.cell.y + 25, 85, data.cell.y + 25);
						},
					});
				}
				var list = [];
				for (let i = 0; i < 1; i++) {
					list.push({
						quotePlanId: '1114512',
						planeModel: '波音747',
						planeYear: '2021',
						siteNum: '2',
						flightPath: '北京-上海',
						flightTime: '2012-9-9',
						quoteAmount: 52,
						remark: '我在哪里'
					});
				}
				for (let i = 0; i < 1; i++) {
					list.push({
						quotePlanId: '1114513',
						planeModel: '波音747',
						planeYear: '2021',
						siteNum: '2',
						flightPath: '北京-上海',
						flightTime: '2012-9-9',
						quoteAmount: 52,
						remark: '我在哪里'
					});
				}
        for (let i = 0; i < 1; i++) {
        	list.push({
        		quotePlanId: '1114514',
        		planeModel: '波音747',
        		planeYear: '2021',
        		siteNum: '2',
        		flightPath: '北京-上海',
        		flightTime: '2012-9-9',
        		quoteAmount: 52,
        		remark: '我在哪里'
        	});
        }
				var map = [];
				for (let i of list) {
					let obj = map.find(j => j.quotePlanId == i.quotePlanId);
					if (!!obj) {
						obj.children.push(i)
					} else {
						obj = {
							quotePlanId: i.quotePlanId,
							remark: i.remark,
							quoteAmount: i.quoteAmount,
							children: []
						}
						obj.children.push(i);
						map.push(obj);
					}
				}
				let tableHeight = 40;
        let falseY = doc.autoTable.previous.finalY;
				for (let i of map) {
					i.breakIndex = i.children.length;
					for (let j = 0; j < i.children.length; j++) {
            tableHeight = !!i.children[j].planeYear ? tableHeight + 33 : tableHeight + 21.5;
            if (pdfHrigth - 30 - falseY - tableHeight < 39) {
              i.breakIndex = j;
              tableHeight = 40;
              falseY = 0;
            }
          }
        }
        //var total = 0;
        let showHeader = "firstPage";
        const rowsTable = [];
        //let caseIndex = 0;
        //let faPage = 0;
        for (let i = 0; i < map.length; i++) {
          for (let j = 0; j < map[i].children.length; j++) {
            const cols = [];
            if (j == 0) {
              cols.push({
                rowSpan: map[i].breakIndex,
                content: `方案${this.TransformToChinese(i + 1)}`,
                styles: {
                  fillColor: [204, 204, 204],
                  halign: "center",
                },
              });
            } else if (j == map[i].breakIndex) {
              cols.push({
								rowSpan: map[i].children.length - map[i].breakIndex,
								content: `方案${this.TransformToChinese(i + 1)}`,
								styles: {
									fillColor: [204, 204, 204],
									halign: "center",
								},
							});
						}
						cols.push(
							map[i].children[j].planeModel +
							(map[i].children[j].planeYear ?
								"\r\n" + "(" + map[i].children[j].planeYear + "年" + ")" :
								"")
						);
						cols.push(map[i].children[j].siteNum);
						cols.push(map[i].children[j].flightPath);
						cols.push(map[i].children[j].flightTime);
						if (j == 0) {
							cols.push({
								rowSpan: map[i].breakIndex,
								content: map[i].quoteAmount,
								styles: {
									halign: "center",
									valign: "middle",
								},
							});
							cols.push({
								rowSpan: map[i].breakIndex,
								content: map[i].remark,
								styles: {
									halign: "center",
									valign: "middle",
								},
							});
						} else if (j == map[i].breakIndex) {
							cols.push({
								rowSpan: map[i].children.length - map[i].breakIndex,
								content: map[i].quoteAmount,
								styles: {
									halign: "center",
									valign: "middle",
								},
							});
							cols.push({
								rowSpan: map[i].children.length - map[i].breakIndex,
								content: map[i].remark,
								styles: {
									halign: "center",
									valign: "middle",
								},
							});
						}
						cols.push(map[i].children[j].siteNum);
						cols.push(map[i].children[j].flightPath);
						cols.push(map[i].children[j].flightTime);
						rowsTable.push(cols);
            if(j == map[i].breakIndex - 1 && map[i].breakIndex != map[i].children.length) {
              drawQuoteTable();
              rowsTable.empty();
            }
					}
				}
        drawQuoteTable();
        function drawQuoteTable() {
          doc.autoTable({
          	styles: {
          		font: "simhei",
          		fontStyle: "normal",
          		overflow: "linebreak",
          		lineColor: [166, 166, 166],
          		lineWidth: 0.5,
          		halign: "center",
          		valign: "middle",
          	},
          	showHeader: showHeader,
          	pageBreak: "auto",
          	head: [["", "机型", "座位数", "飞行路线", "飞行时长", "总价", "备注"]],
          	body: rowsTable,
          	headStyles: {
          		fillColor: [191, 191, 191],
          		textColor: [0, 0, 0],
          		minCellHeight: 30,
          	},
          	bodyStyles: {
          		textColor: [0, 0, 0],
          	},
          	theme: "grid",
          	startY: doc.autoTable.previous.finalY + 10,
          	margin: {
          		left: 17,
          		right: 15
          	},
          });
          showHeader = "never";
          console.log('表格画完后剩下的高度：', pdfHrigth - 30 - doc.autoTable.previous.finalY);
        }
				if (pdfHrigth - 30 - doc.autoTable.previous.finalY < 55) {
					doc.addPage();
					doc.autoTable(0, [{
						id: ""
					}], {
						styles: {
							cellWidth: "auto",
							font: "simhei",
							fontStyle: "normal",
							lineColor: [166, 166, 166],
							minCellHeight: 25,
						},
						theme: "plain",
						startY: 25,
						margin: {
							left: 15,
							right: 15
						},
						didDrawCell: (data) => {
							// 注意事项
							doc.setFontSize(16);
							doc.setTextColor(0, 0, 0);
							doc.text("注意事项", 20, data.cell.y + 15);
							doc.setDrawColor(128, 128, 128);
							doc.setLineWidth(1.5);
							doc.line(20, data.cell.y + 25, 85, data.cell.y + 25);
						},
					});
				} else {
					doc.autoTable(0, [{
						id: ""
					}], {
						styles: {
							cellWidth: "auto",
							font: "simhei",
							fontStyle: "normal",
							lineColor: [166, 166, 166],
							minCellHeight: 25,
						},
						theme: "plain",
						startY: doc.autoTable.previous.finalY + 30,
						margin: {
							left: 15,
							right: 15
						},
						didDrawCell: (data) => {
							// 注意事项
							doc.setFontSize(16);
							doc.setTextColor(0, 0, 0);
							doc.text("注意事项", 20, data.cell.y + 15);
							doc.setDrawColor(128, 128, 128);
							doc.setLineWidth(1.5);
							doc.line(20, data.cell.y + 25, 85, data.cell.y + 25);
						},
					});
				}
        var zhuyishixiang = (s) => {
          // 注意事项下面的文字
          if (pdfHrigth - 30 - doc.autoTable.previous.finalY < 100) {
            console.log('文字没有写剩下的高度：', pdfHrigth - 30 - doc.autoTable.previous.finalY);
          	doc.addPage();
          	doc.autoTable(0, [{
          		id: ""
          	}], {
          		styles: {
          			cellWidth: "auto",
          			font: "simhei",
          			fontStyle: "normal",
          			lineColor: [166, 166, 166],
          			minCellHeight: 80,
          		},
          		theme: "plain",
          		startY: 25,
          		margin: {
          			left: 15,
          			right: 15
          		},
          		didDrawCell: (data) => {
          			doc.setFontSize(10);
          			doc.setTextColor(0, 0, 0);
          			doc.text(
          				doc.splitTextToSize(
          					s,
          					550
          				),
          				20,
          				data.cell.y + 10, {
          					lineHeightFactor: 2
          				}
          			);
          		},
          	});
            console.log('文字写完后剩下的高度：', pdfHrigth - 30 - doc.autoTable.previous.finalY);
          } else {
            console.log('文字没有写剩下的高度：', pdfHrigth - 30 - doc.autoTable.previous.finalY);
          	doc.autoTable(0, [{
          		id: ""
          	}], {
          		styles: {
          			cellWidth: "auto",
          			font: "simhei",
          			fontStyle: "normal",
          			lineColor: [166, 166, 166],
          			minCellHeight: 80,
          		},
          		theme: "plain",
          		startY: doc.autoTable.previous.finalY + 20,
          		margin: {
          			left: 15,
          			right: 15
          		},
          		didDrawCell: (data) => {
          			doc.setFontSize(10);
          			doc.setTextColor(0, 0, 0);
          			doc.text(
          				doc.splitTextToSize(
          					s,
          					550
          				),
          				20,
          				data.cell.y + 10, {
          					lineHeightFactor: 2
          				}
          			);
          		},
          	});
            console.log('文字写完后剩下的高度：', pdfHrigth - 30 - doc.autoTable.previous.finalY);
          }
        }
				zhuyishixiang("* 总价包含基础飞行费用、机场费用、地面服务费用、标准的餐食费用，不包含其他增值服务产生的额外费用。" +
          					"费用含税，中国大陆境内行程开具增值税专用发票，跨境行程开具增值税普通发票。\n" +
          					"* 行程是否可执行与您确认的飞行日期、航段、时刻以及航空公司实际运力相关,如确认飞行,请尽快与我们联系。\n" +
          					"* 方案中推荐机型图片请见报价单附录。\n" +
                    "* 本报价单不具备与合同相同的法律效力，48小时内有效。")
        zhuyishixiang("* 总价包含基础飞行费用、机场费用、地面服务费用、标准的餐食费用，不包含其他增值服务产生的额外费用。" +
          					"费用含税，中国大陆境内行程开具增值税专用发票，跨境行程开具增值税普通发票。\n" +
          					"* 行程是否可执行与您确认的飞行日期、航段、时刻以及航空公司实际运力相关,如确认飞行,请尽快与我们联系。\n" +
          					"* 方案中推荐机型图片请见报价单附录。")
				// 行程示例
				doc.addPage();
				doc.autoTable(0, [{
					id: ""
				}], {
					styles: {
						cellWidth: "auto",
						font: "simhei",
						fontStyle: "normal",
						lineColor: [166, 166, 166],
						minCellHeight: 25,
					},
					theme: "plain",
					startY: 25,
					margin: {
						left: 15,
						right: 15
					},
					didDrawCell: (data) => {
						// 行程示例
						doc.setFontSize(16);
						doc.setTextColor(0, 0, 0);
						doc.text("行程示例", 20, data.cell.y + 15);
						doc.setDrawColor(128, 128, 128);
						doc.setLineWidth(1.5);
						doc.line(20, data.cell.y + 25, 85, data.cell.y + 25);
					},
				});
				if (pdfHrigth - 30 - doc.autoTable.previous.finalY < 275) {
					doc.addPage();
					doc.autoTable(0, [{
						id: ""
					}], {
						styles: {
							cellWidth: "auto",
							font: "simhei",
							fontStyle: "normal",
							lineColor: [166, 166, 166],
							minCellHeight: 200,
						},
						theme: "plain",
						startY: 25,
						margin: {
							left: 30,
							right: 15
						},
						didDrawCell: (data) => {
							try {
								doc.addImage(
									this.img,
									"PNG",
									data.cell.x,
									data.cell.y,
									data.cell.width,
									200
								);
							} catch (err) {
								console.log(err);
							}
						},
					});
				} else {
					doc.autoTable(0, [{
						id: ""
					}], {
						styles: {
							cellWidth: "auto",
							font: "simhei",
							fontStyle: "normal",
							lineColor: [166, 166, 166],
							minCellHeight: 200,
						},
						theme: "grid",
						startY: doc.autoTable.previous.finalY + 30,
						margin: {
							left: 30,
							right: 15
						},
						didDrawCell: (data) => {
							try {
								doc.addImage(
									this.img,
									"PNG",
									data.cell.x,
									data.cell.y,
									data.cell.width,
									200
								);
							} catch (err) {
								console.log(err);
							}
						},
					});
				}
				setTimeout(() => {
					let blob = this.dataURLtoBlob(doc.output("datauristring"));
					this.$refs.preview.src = URL.createObjectURL(blob); //在iframe中显示
				}, 300);
			},
			TransformToChinese(num) {
				let changeNum = [
					"零",
					"一",
					"二",
					"三",
					"四",
					"五",
					"六",
					"七",
					"八",
					"九",
				];
				let unit = ["", "十", "百", "千", "万"];
				num = parseInt(num);
				let getWan = (temp) => {
					let strArr = temp.toString().split("").reverse();
					let newNum = "";
					for (var i = 0; i < strArr.length; i++) {
						newNum =
							(i == 0 && strArr[i] == 0 ?
								"" :
								i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ?
								"" :
								changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) +
							newNum;
					}
					return newNum;
				};
				let overWan = Math.floor(num / 10000);
				let noWan = num % 10000;
				if (noWan.toString().length < 4) {
					noWan = "0" + noWan;
				}
				return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
			},
			initMap() {
				//清空缓存
				let orderDetailList = [];
				let chat = this;
				this.mapData = [];
				mapboxgl.accessToken = this.mapToken;
				const map = new mapboxgl.Map({
					container: this.$refs.map,
					style: 'mapbox://styles/mapbox/dark-v10',
					center: [109.05257932529969, 34.341575935317664],
					zoom: 4,
					dragRotate: false,
					scrollZoom: false,
					preserveDrawingBuffer: true,
				});
				map.on("load", () => {
					let features = [];
					features.push({
						type: "Feature",
						geometry: {
							type: "Point",
							coordinates: [
								108.35,
								35.15245,
							],
						},
						properties: {
							title: '西安'
						},
					});
					features.push({
						type: "Feature",
						geometry: {
							type: "Point",
							coordinates: [
								121.35,
								31.15245,
							],
						},
						properties: {
							title: '上海'
						},
					});
					map.addLayer({
						id: "circle00",
						type: "circle",
						source: {
							type: "geojson",
							data: {
								type: "FeatureCollection",
								features: features,
							},
						},
						paint: {
							"circle-radius": 6,
							"circle-color": "#000",
						},
					});
					map.addLayer({
						id: "route",
						type: "line",
						source: {
							type: "geojson",
							data: {
								type: "Feature",
								properties: {},
								geometry: {
									type: "LineString",
									coordinates: [
										[
											108.35,
											35.3654,
										],
										[
											121.3654,
											31.15245,
										],
									],
								},
							},
						},
						layout: {
							"line-join": "round",
							"line-cap": "round",
						},
						paint: {
							"line-color": "#888",
							"line-width": 6,
						},
					});
          let minLong = Math.min(108.35, 121.3654);
          let maxLong = Math.max(108.35, 121.3654);
          let minLat = Math.min(35.3654, 31.15245);
          let maxLat = Math.max(35.3654, 31.15245);
          map.fitBounds(
            [
              [minLong, minLat],
              [maxLong, maxLat],
            ],
            {
              padding: { top: 70, bottom: 70, left: 70, right: 70 },
            }
          );
					/**动态加载*/
					map.once("moveend", () => {
						setTimeout(() => {
							let content = map.getCanvas().toDataURL();
							chat.img = content;
							chat.getDownLoadPdf();
						}, 3000);
					});
				});
			}
		}
	}
</script>

<style>
</style>
